import { reqCartList, reqDeleteCartById, reqChangeCartById } from '@/api'
const state = {
    cartList: []
}
const actions = {
    // 获取购物车列表数据
    async getCartList ({ commit }) {
        let res = await reqCartList()

        if (res.code == 200) {
            commit('GETCARTLIST', res.data)
        }
    },
    //删除购物车某一个产品
    async deleteCartListBySkuId ({ commit }, skuId) {
        let res = await reqDeleteCartById(skuId)
        if (res.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 修改购物车某一个产品选中的状态
    async updateCheckedById ({ commit }, { skuId, isChecked }) {
        let res = await reqChangeCartById(skuId, isChecked)
        // console.log(res);
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise(new Error('faile'))
        }
    },
    //删除全部勾选的产品
    deleteAllCheckedCart ({ dispatch, getters }) {
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            let res = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : '';
            PromiseAll.push(res)
        });
        return Promise.all(PromiseAll)
    },
    // 修改全选状态
    updateAllCartIsChecked ({ dispatch, state }, isChecked) {
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked });
            PromiseAll.push(promise)

        })
        return Promise.all(PromiseAll);
    }
}
const mutations = {
    GETCARTLIST (state, cartList) {
        state.cartList = cartList
    }
}
const getters = {
    cartList (state) {
        return state.cartList[0] || []
    },
    //计算出购物出来的属性

}
export default {
    state, actions, mutations, getters
}